<?php

/**
 * @author jrodriguez
 * @copyright 2013
 */
require_once("../../PathHelper.php");
require_once $rootPath.'Gazzetta.DAL/Repositories/BaseRepository.php';

class RSSItemRepository extends BaseRepository 
{
    public function __construct()
    {
        $this->tableName = 'RSSItem';    
    }
    
    public function formatOne($row)
    {
        $rsssource = new RSSItem();
        
        foreach ($row as $field => $value) 
        {
       		if($field == 'Id')
                 $rsssource->setId($value);            
            else if($field == 'Link')            
                 $rsssource->setLink($value);
            
            else if($field == 'Title')            
                 $rsssource->setTitle($value);
            
            else if($field == 'Description')            
                 $rsssource->setDescription($value);
            
            else if($field == 'IdRSSSource')            
            	$rsssource->setIdRSSSource($value); 
            
            else if($field == 'ImageLink')            
            	$rsssource->setImageLink($value);  
            
            else if($field == 'PubDate')            
            	$rsssource->setPubDate($value);  
        }          
                 
        return $rsssource;
    }   
    
    protected function buildColumnsPartForInsert()
    {
        $sql = "`Link`,`Title`, `Description`, `IdRSSSource`, `ImageLink`, `PubDate`";
        return $sql;
    }
    
    protected function buildValuesPartForInsert($entity)
    {
        $sql = '\''.$entity->getLink(). '\',\''. $entity->getTitle() . '\',\''. $entity->getDescription() . '\',\''. $entity->getIdRSSSource(). '\',\''. $entity->getImageLink() . '\',\''.  $entity->getPubDate()->format('Y-m-d H:i:s').'\'';
       
        return $sql;
    }
    
    public function getRSSItemsByCategory($category, $limit)
    {
    	$conn = $this->buildConnection();
    	$result = $conn->getResultSet('SELECT RSSITEM.* FROM RSSITEM 
										INNER JOIN rssSource ON rsssource.Id = rssitem.IdRSSSource
										INNER JOIN rssCategory ON rssCategory.Id = rsssource.IdCategory
										WHERE RSSCategory.Name = \'' . $category . '\'
                                        ORDER BY Pubdate DESC 
                                        LIMIT '.$limit);
    	return $this->formatCollection($result);
    }
      
    public function exists($link)
    {
    	$conn = parent::buildConnection();
    	$result = $conn->getResultSet('SELECT * FROM RSSITEM
										WHERE Link = \'' . $link . '\'');
    	return $result->count() > 0;
    }
    
    public function getAmountBySourceId($sourceId)
    {
    	$result =  $this->getWithWhere(' WHERE IdRSSSource = '.$sourceId);
        $count = $result->count();
        return $count;
    }
}

?>